#pragma once
#include <iostream>
#include <string>
#include <stdarg.h>
#include <ctime>
#include <unistd.h>
#include <fstream>

#define LOG_NORMAL "log.txt"
#define LOG_ERR "log.err"

enum level
{
    DEBUG = 0,
    NORMAL,
    WARNING,
    ERROR,
    FAULT,
};

std::string lvtostring(level &lv)
{
    switch (lv)
    {
    case DEBUG:
        return "DEBUG";
    case NORMAL:
        return "NORMAL";
    case WARNING:
        return "WARNING";
    case ERROR:
        return "ERROR";
    case FAULT:
        return "FAULT";
    default:
        break;
    }
    return nullptr;
}
void logMessage(level lv, const char *format, ...)
{
    std::string loglv = lvtostring(lv);
#define NUM 1024
    char logprefix[NUM];
    snprintf(logprefix, sizeof(logprefix) - 1, "[%s][%ld][pid:%d]:", loglv.c_str(), (long int)time(nullptr), getpid());
    char logcontext[NUM];
    va_list arg;
    va_start(arg, format);
    vsnprintf(logcontext, sizeof(logcontext), format, arg);
    std::ofstream log(LOG_NORMAL, std::ios::app);
    std::ofstream err(LOG_ERR, std::ios::app);
    if(log.good() && err.good())
    {
        switch (lv)
        {
        case DEBUG:
        case NORMAL:
        case WARNING:
            log << logprefix << logcontext << std::endl;
            break;
        case ERROR:
        case FAULT:
            err << logprefix << logcontext << std::endl;
            break;
        default:
            break;
        }
    }
    else
        return;
    log.close();
    err.close();
}
